//
//  SstDevice.m
//  IOS_SST
//
//  Created by lfy on 16/4/25.
//  Copyright © 2016年 secsmarts.com. All rights reserved.
//

#import "SstDevice.h"
#include "sstComstruct.h"
#include "KeyManage.h"

#import "sstNSStringFormat.h"

@implementation SstDevice

@synthesize deviceID;
@synthesize mac;
@synthesize ip;

@synthesize hexToken;

@synthesize udpKey;
@synthesize tcpKey;

@synthesize hexUdpKeyID;
@synthesize k1;

@synthesize ssidKey;
@synthesize port;
@synthesize hasGetR3;

-(id) init
{
    if(self = [super init])
    {
        ssidKey = malloc(HASH_DIGEST_LEN);
        udpKey = nil;
        k1 = malloc(HASH_DIGEST_LEN);
        get_random_bytes(k1, LICENSE_KEY_LEN);
    }
    
    return self;
}

-(void)setK1: (u8 *)newk1
{
    if (k1 == nil)
        return;
    
    if (k1 != nil)
        free(k1);
   
    k1 = malloc(HASH_DIGEST_LEN);
    memcpy(k1, newk1, HASH_DIGEST_LEN);
}

-(void)setTcpK2:(u8 *)newk2
{
    if (newk2 == nil)
        return;
    
    [self clearTcpKey];
    tcpKey = malloc(HASH_DIGEST_LEN);
    LogHex("K1", self.k1, HASH_DIGEST_LEN);
    [KeyManage xorData: tcpKey withInput1:k1 withInput2:newk2 withLen: HASH_DIGEST_LEN];
    LogHex("tcpKey", tcpKey, HASH_DIGEST_LEN);
}

-(void)setUdpK2:(u8 *)newk2
{
    if (newk2 == nil)
        return;
   
    [self clearUdpKey];
    udpKey = malloc(HASH_DIGEST_LEN);
    LogHex("K1", self.k1, HASH_DIGEST_LEN);
    [KeyManage xorData: udpKey withInput1:k1 withInput2:newk2 withLen: HASH_DIGEST_LEN];
    LogHex("udpKey", udpKey, HASH_DIGEST_LEN);
}

-(u8 *)getSsidKey
{
    return ssidKey;
}

-(void)setSsidKey:(u8 *)newSsidKey
{
    if (newSsidKey == nil)
        return;
    if (ssidKey != nil)
    {
        free(ssidKey);
    }
    ssidKey = malloc(HASH_DIGEST_LEN);
    memcpy(ssidKey, newSsidKey, HASH_DIGEST_LEN);
}

-(void) clearUdpKey
{
    if (udpKey != nil)
    {
        free(udpKey);
        udpKey = nil;
    }
}

-(void)clearTcpKey
{
    if (tcpKey != nil)
    {
        free(tcpKey);
        tcpKey = nil;
    }
}

-(Boolean)getUdpIsHandShaked
{
    Boolean result = udpKey != nil;
    NSLog(@"getUdpIsHandShaked = %d", result);
    return result;
}

-(Boolean)getTcpIsHandShaked
{
    Boolean result = tcpKey != nil;
    //NSLog(@"getTcpIsHandShaked = %d", result);
    return result;
}

-(void)setHexUdpKeyID: (u8 *) newHexUdpKeyID
{
    if (newHexUdpKeyID == nil)
        return;
    
    if (hexUdpKeyID != nil)
    {
        if(memcmp(newHexUdpKeyID, hexUdpKeyID, UDP_KEY_ID_LEN) == 0)
            return;
        
        free(hexUdpKeyID);
    }
    
    LogHex("newHexUdpKeyID", newHexUdpKeyID, UDP_KEY_ID_LEN);
    hexUdpKeyID = malloc(UDP_KEY_ID_LEN);
    memcpy(hexUdpKeyID, newHexUdpKeyID, UDP_KEY_ID_LEN);
}

-(void)setHexToken: (u8 *) newToken
{
    if (newToken == nil)
        return;
    
    if (hexToken != nil)
        free(hexToken);
    
    hexToken = malloc(TOKEN_LENGTH);
    memcpy(hexToken, newToken, TOKEN_LENGTH);
}
@end
